package com.situ.student.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.Session;

import com.situ.student.entity.Banji;
import com.situ.student.entity.PageBean;
import com.situ.student.entity.Student;
import com.situ.student.entity.StudentSearchCondition;
import com.situ.student.service.IBanjiService;
import com.situ.student.service.IStudentService;
import com.situ.student.service.impl.BanjiServiceImpl;
import com.situ.student.service.impl.StudentServiceImpl;

public class StudentController extends HttpServlet {
	private IStudentService studentService = new StudentServiceImpl();
	private IBanjiService banjiService = new BanjiServiceImpl();
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println(req.getContextPath());//打印项目名 Java1807Web
		System.out.println(req.getServletPath());// student
		System.out.println(req.getRequestURI());// Java1807Web/student
		System.out.println(req.getRequestURI());
		
		/*//判断用户有没有登陆
		HttpSession session = req.getSession();//建立session
		User user = (User) session.getAttribute("user");
		if (user == null) {
			resp.sendRedirect(req.getContextPath()+"/login.jsp");
			return;
		}*/
		
		/*post乱码问题，由Filter过滤器已解决
		 * request.setCharacterEncoding("UTF-8");
		 * */
		String method = req.getParameter("method");//传过来的方法
		switch (method) {
		//展示
		case "list":
			list(req, resp);
			break;
		//根据id删除	
		case "deleteById":
			deleteById(req, resp);
			break;
		//批量删除
		case "deleteAll":
			deleteAll(req, resp);
			break;	
		
		//添加	
		case "insert":
			insert(req, resp);
			break;
		//修改	
		case "toUpdate":
			toUpdate(req,resp);
			break;
			
		case "update":
			update(req,resp);
			break;
		//分页
		case "pageList":
			pageList(req, resp);
			break;
		//ajax,使添加名字不重复	
		case "checkName":
			checkName(req, resp);
			break;	
		//添加页面显示班级
		case "getAddPage":
			getAddPage(req, resp);
			break;		
		default:
			break;
		}
	}
	
	//添加页面可选择班级
	//查出所有班级信息，放到域对象，转发student_add,jsp页面
	private void getAddPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<Banji> list = banjiService.list();
		req.setAttribute("list", list);
		req.getRequestDispatcher("/student_add.jsp").forward(req, resp);
	}


	//ajax,使添加名字不重复	
	private void checkName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String name = req.getParameter("name");
		boolean isExist =  studentService.checkName(name);
		resp.setContentType("text/html;charset=utf-8");
		resp.getWriter().write("{\"isExist\": "+isExist+"}");
	}

	private void deleteAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String[] selectIds = req.getParameterValues("selectIds");
		System.out.println(Arrays.toString(selectIds));
		studentService.deleteAll(selectIds);
		resp.sendRedirect(req.getContextPath() + "/student?method=pageList");
		
	}
	private void pageList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//接受请求参数，封装成对象
		String pageNoStr = req.getParameter("pageNo"); //接受到浏览器的请求
		if (pageNoStr == null || pageNoStr.equals("")) {
			pageNoStr = "1";
		}
		int pageNo = Integer.parseInt(pageNoStr);
		
		String pageSizeStr = req.getParameter("pageSize");
		if (pageSizeStr == null || pageSizeStr.equals("")) {
			pageSizeStr = "3";
		}
		int pageSize = Integer.parseInt(pageSizeStr);
		String name = req.getParameter("name");
		String ageStr = req.getParameter("age");
		Integer age = null;
		if (ageStr != null && !"".equals(ageStr)) {
			age = Integer.parseInt(ageStr);
		}
		String gender = req.getParameter("gender");
		//所有要查询的条件封装
		StudentSearchCondition searchCondition = new StudentSearchCondition(pageNo, pageSize, name, age, gender);
		
		//封装成pageBean，调用业务逻辑
		PageBean<Map<String, Object>> pageBean = studentService.getPageBean(searchCondition);
		System.out.println(pageBean);
		//控制界面跳转
		req.setAttribute("pageBean", pageBean); //要展示分页的信息
		req.setAttribute("searchCondition", searchCondition);
		req.getRequestDispatcher("student_list.jsp").forward(req, resp);//转发出去
	}
	
	
	//真正修改
	private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		//1、得到浏览器输入的参数信息
				Integer id = Integer.parseInt(req.getParameter("id"));
				String name = req.getParameter("name");
				Integer age = Integer.parseInt(req.getParameter("age"));
				String gender = req.getParameter("gender");
				Integer banjiId = Integer.parseInt( req.getParameter("banjiId"));
				Student student = new Student(id, name, age, gender, banjiId);
				//Student student = new Student(id, name, age, gender);
				//2、调用sevice
				boolean result = studentService.update(student);
				System.out.println(result ? "成功" : "失败");
				//3、重定向
				resp.sendRedirect(req.getContextPath()+"/student?method=pageList");//防止项目名写死
	}

	//欲修改
	private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//根据ID查出要修改的学生对象
		Integer id = Integer.parseInt(req.getParameter("id"));
		Student student =  studentService.findById(id);//根据查找指定学生对象，直接使用
		//显示班级列表
		List<Banji> list = banjiService.list();
		req.setAttribute("list", list);
		//转发到student_update.jsp页面
		req.setAttribute("student", student);
		req.getRequestDispatcher("/student_update.jsp").forward(req, resp); 
		//resp.getWriter().write(student.toString());
	}
	
	//添加
	private void insert(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		//1、得到浏览器输入的参数信息
		String name = req.getParameter("name");
		Integer age = Integer.parseInt(req.getParameter("age"));
		String gender = req.getParameter("gender");
		Integer banjiId = Integer.parseInt(req.getParameter("banjiId"));
		Student student = new Student(name, age, gender, banjiId); //页面展示班级
		
		//2、调用sevice
		boolean result = studentService.insert(student);
		System.out.println(result ? "成功" : "失败");
		//3、重定向
//		resp.sendRedirect(req.getContextPath() +"/student?method=list");//原list
		resp.sendRedirect(req.getContextPath() +"/student?method=pageList");
	}

	//删除根据ID
	private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		//1、得到浏览器传递过来的参数信息
		//拿到int类型的id
		Integer id = Integer.parseInt(req.getParameter("id"));
		//2、调用service处理
		// deleteById调用了service中的deleteById
		boolean deresult = studentService.deleteById(id);
		//布尔
		resp.setContentType("text/html;charset=utf-8");
		resp.getWriter().write("{\"deresult\": "+deresult+"}");
		System.out.println(deresult ? "成功" : "失败");
		
		//3、重定向到列表界面
		resp.sendRedirect(req.getContextPath() +"/student?method=pageList");
		//转发
		//req.getRequestDispatcher("/student_list.jsp").forward(req, resp);
	}
	
   //展示
	private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//List<Student> list = studentService.list();//service方法得到列表
		
		String name = req.getParameter("name");
		//调用service
		List<Student> list = new ArrayList<>();
		if (name == null || name.equals("")) {//查找所有
		list = studentService.list(); //
			} else {
		
	/*	//模糊查找
		list = studentService.findByName(name);
		list = new ArrayList<>();
		Student student = new Student(22, name + " Java1807", 30, "男");
		list.add(student);
		}
		req.setAttribute("list", list);*/
		
		//展示
		for (Student student : list) {  //遍历
			System.out.println(student);
		}
		//list放到req里面
		req.setAttribute("list", list);
		//转发页面展示
		req.getRequestDispatcher("student_list.jsp").forward(req, resp);
		}	
	}
}	
